using System.Linq.Expressions;
using CMS.EFCore;
using CMS.Entity;

namespace CMS.Repository.Impl;

public class BaseRepository<T>(MyDbContext myDbContext) where T : class, new() {
    public IQueryable<T> Get(Expression<Func<T, bool>> whereLambda) {
        return myDbContext.Set<T>().Where(whereLambda);
    }
    
    public IQueryable<T> GetPage<TS>(int pageIndex, int pageSize, out int totalCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TS>> orderByLambda,
                                    bool isAsc) {
        var temp = myDbContext.Set<T>().Where(whereLambda);
        totalCount = temp.Count();
        if (isAsc)
        {
            // 升序
            temp = temp.OrderBy<T, TS>(orderByLambda).Skip<T>((pageIndex-1)*pageSize).Take<T>(pageSize);
        }
        else
        {
            temp = temp.OrderByDescending<T, TS>(orderByLambda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);
        }
        return temp;
    }

    public async Task<bool> AddAsync(T entity) {
        await myDbContext.Set<T>().AddAsync(entity);
        return await Task.FromResult(true);
    }

    public Task<bool> UpdateAsync(T entity) {
        myDbContext.Set<T>().Update(entity);
        return Task.FromResult(true);
    }

    public Task<bool> DeleteAsync(T entity) {
        myDbContext.Set<T>().Remove(entity);
        return Task.FromResult(true);
    }
}